<?php
/**
 * User zgh
 * Email 1803897171@qq.com
 * Date 2021/7/11
 **/

namespace app\common\service;



use app\common\item\BaseItemLoader;
use app\common\model\SysConfigModel;
use app\common\pipeline\BaseItemAdapter;
use app\common\util\RedisUtil;
use think\facade\Env;
use think\facade\Hook;

class SysConfigService
{

    public static function getByID($id = 1)
    {
        $adapter = new BaseItemAdapter(SysConfigModel::class);
        return $adapter->get($id)->getModel();
    }

    public static function clearCache()
    {
        RedisUtil::getInstance()->redisHandler()->del(\CacheKeyMap::sysConfigHash());
        return true;
    }

    public static function saveCache($id = 1)
    {
        $adapter = new BaseItemAdapter(SysConfigModel::class);
        $data = $adapter->get($id)->getData();
        RedisUtil::getInstance()->redisHandler()->hMSet(\CacheKeyMap::sysConfigHash(), $data);
        return true;
    }

    public static function getAll()
    {
        $arr = RedisUtil::getInstance()->redisHandler()->hGetAll(\CacheKeyMap::sysConfigHash());
        if (!$arr) {
            self::updateCache();
            $arr = RedisUtil::getInstance()->redisHandler()->hGetAll(\CacheKeyMap::sysConfigHash());
        }
        return $arr;
    }


    public static function getConfig($key = "")
    {
        $arr = self::getAll();
        if (!empty($key)) {
            return $arr[$key];
        } else {
            return $arr;
        }
    }


    /**
     * 更新缓存
     */
    protected static function updateCache()
    {
        self::clearCache();
        self::saveCache();
        return true;
    }

    public static function save($params)
    {
        //更新缓存
        $loader = new BaseItemLoader();
        $data = $loader->addVal($params)->loadItem();
        $adapter = new BaseItemAdapter(SysConfigModel::class);
        $adapter->get(1);
        Hook::add("sys_config_save", function ($params) {
            $content = @file_get_contents($params['site_icon']);
            @file_put_contents(Env::get("app_path") . "/../public/favicon.ico", $content); //将icon 放在根目录下
            self::updateCache();
        });
        return $adapter->hookAdd("sys_config_save", $data)->save($data);
    }
}